package newx.com.control
{
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	
	import newx.com.NxUIComponent;
	import newx.com.ResManager;
	import newx.com.loader.SwfLoader;
	
	/**
	 * 
	 * 集成了Image和Sprite的功能，可以用来加载图片和swf资源，
	 * 也可以作为容器添加其他显示对象到容器内。<br>
	 * 支持编辑器。
	 * @author lw
	 * 
	 */
	public class NxClip extends NxUIComponent implements IClip
	{
		/**
		 *	加载失败 
		 */
		public static const NXCLIP_IOERROR : String = IOErrorEvent.IO_ERROR;
		
		/**
		 * 	加载进度
		 */
		public static const NXCLIP_PROGRESS: String = ProgressEvent.PROGRESS;
		
		/**
		 * 	加载完成
		 */
		public static const NXCLIP_COMPLETE: String = Event.COMPLETE;
		
		public static const NXCLIP_ADDED   : String = Event.ADDED;
		
		private	var _eventList		: Array				=		[];
		
		private	var _isCache		: Boolean			=		false;
		
		private	var	_autoLoad		: Boolean			=		true;
		
		private	var _aspectRatio	: Boolean			=		true;
		
		private	var _scaleContent	: Boolean			=		false;
		
		private	var	_defaultImage	: DisplayObject;
		
		public 		var defaultSkin		: String			=		"";
		
		/**
		 *	正在加载 
		 */		
		private	var _isLoading		: Boolean			=		false;
		
		/**
		 * 新设的资源 
		 */		
		private	var _newSource		: Object;
		
		private	var _source			: Object;
		
		private	var _content		: DisplayObject;
		
		private 	var	_contentWidth	: int				=		40;
		
		private	var	_contentHeight	: int				=		40;
		
		private	var	_width			: int				=		40;
		
		private 	var _height			: int				=		40;
		
		private	var _bytesLoaded	: uint				=		0;
		
		private	var _bytesTotal		: uint				=		0;
		
		private	var	_percentLoaded	: Number			=		1;
		
		
		/**
		 * 	加载
		 */
		private function loadRes() : void
		{
			//当是显示元件的时候
			if(_source is DisplayObject)
			{
//				trace(_name,"从source is DisplayObject");
				addRes(_source as DisplayObject);
				
				return;
			}
			
			//当时url，类名等
			if(_source is String)
			{
				var tRes : DisplayObject;
				
				if(_source == "")
				{
//					trace(_name,"从_source 为空");
					addRes(null,null);
					return;
				}
				
				if( ResManager.isResHave( String(_source) ))
				{
					tRes	=	ResManager.getResContentCopy(String(_source));
				}else
				{
					tRes	=	ResManager.newResClass(String(_source));
				}
				
				if(tRes == null)
				{
					if( null == _defaultImage && defaultSkin != "")
					{
						_defaultImage =ResManager.newResClass(defaultSkin);
					}else
					{
						if( _defaultImage is MovieClip)
						{
							MovieClip(_defaultImage).play();
						}
					}
					
					_content	=	_defaultImage;
					
					if(_content != null)
					{
						addChild(_content);
//						updataContent();
					}
					
					if(_isCache)
					{
						ResManager.loadRes(String(_source),String(_source),addRes,[true]);
						//						trace(_name,"从ResManager.loadRes");
					}
					else 
					{
						SwfLoader.StartLoad(String(_source),this,addRes,[eventModel]);
						//						trace(_name,"从SwfLoader.StartLoad");
					}										
				}		
				else
				{
					addRes(tRes);
				}
				
				
			}
			else//不识别的数据类型
			{
				addRes(null,null);
			}
		}
		
		/**
		 *	添加显示元件 
		 * @param val				显示元件
		 * @param pList				参数
		 * 
		 */
		private function addRes(val:DisplayObject,pList:Array = null):void
		{
//			trace(_name,"加载完成！！--------->当前_source:"+_source,"---->_newSource:"+_newSource,"-------->mc："+((null!=val)? (null!=val.loaderInfo?val.loaderInfo.url:"无LoaderInfo"):"空"));
			
			removeAll();
			if(val == null)
			{
				_isLoading	=	false;
				
				if(	_newSource	!=	_source	)
				{
					source	=	_newSource;
				}
				
				return;
			}
			
			if(null != pList && !(pList[0] is Function) && pList[0])
			{
				_content	=	ResManager.copy(val);
			}else
			{
				_content = val;
			}
//			
			addChild(_content);
			updataContent();
			
			_isLoading	=	false;
			
			if(	_newSource	!=	_source	)
			{
				source	=	_newSource;
			}
			
			if( _content is Sprite )
			{
				( _content as Sprite ).mouseChildren = ( _content as Sprite ).mouseEnabled = false;
			}
		}
		
		
		/**
		 *	更新显示元件大小 
		 */
		private function updataContent() : void
		{
			if(_content == null) return;
			//适应控件大小
			if(_scaleContent)
			{
				//比例缩小,放大
				if(_aspectRatio)
				{
					//获得比例
					var scaleWidth : Number = _contentWidth / _width;
					var scaleHeight : Number = _contentHeight / _height;
					var scale : Number;
					scale = Math.max(scaleWidth, scaleHeight);
					_contentWidth = _contentWidth / scale;
					_contentHeight = _contentHeight / scale;
				}
				else
				{
					_contentWidth	=	_width;
					_contentHeight	=	_height;
				}
					
				_content.width = _contentWidth;
				_content.height = _contentHeight;
			}
			else
			{
				_contentWidth = _content.width;
				_contentHeight = _content.height
				_width = _content.width;
				_height = _content.height;
			}
		}
		
		/**
		 *	事件集中处理函数 
		 * bug 缓存后的控件（isCache为true，默认是true），将不会触发complete事件
		 * @param evt
		 * 
		 */
		private function eventModel(evt : Event) : void
		{
			if(evt.type == NXCLIP_PROGRESS)
			{
				loadProgress(evt as ProgressEvent);
			}
			for each(var event : Array in _eventList)
			{
				if(evt.type == event[0])
				{
					(event[1] as Function).call(this, evt.target.content);
				}
			}
		}
		
		private function loadProgress(evt : ProgressEvent) : void
		{
			_bytesLoaded = evt.bytesLoaded;
			_bytesTotal = evt.bytesTotal;
			
			_percentLoaded = _bytesLoaded / _bytesTotal;
		}
		
		private var _name:String;
		
		public function set clipName(name:String):void
		{
			_name	=	name;
		}
		
		public function set source(val:Object):void
		{
//			trace(_name,"设置Source！！----->当前_source:"+_source,"---->_newSource:"+_newSource,"------------>是否在加载："+_isLoading);
			if( "" == val || val ==null)
			{
				_source = "";
				removeAll();
			}

			if(	true	==	_isLoading)
			{
				_newSource	=	val;
				return;
			}
			
			if( _source === val && _content != null) return;
			
			_source = val;
			_newSource	=	val;
			
			_bytesLoaded = 0;
			_bytesTotal = 0;
			_percentLoaded = 1;
			
			//当不自动的时候，等待手动开启
			if(!autoLoad || val == "") return;
			
			_isLoading	=	true;
			
			loadRes();
		}
		
		public function get source():Object
		{
			return _source;
		}
		
		public function get defaultImage():DisplayObject
		{
			return _defaultImage;
		}
		
		public function set defaultImage(val:DisplayObject):void
		{
			_defaultImage = val;
		}
		
		public function get autoLoad():Boolean
		{
			return _autoLoad;
		}
		
		public function set autoLoad(val:Boolean):void
		{
			_autoLoad = val;
		}
		
		public function get isCache():Boolean
		{
			return _isCache;
		}
		
		public function set isCache(val:Boolean):void
		{
			_isCache = val;
		}
		
		public function get bytesLoaded():uint
		{
			return _bytesLoaded;
		}
		
		public function get bytesTotal():uint
		{
			return _bytesTotal;
		}
		
		public function get percentLoaded():Number
		{
			return _percentLoaded;
		}
		
		public function get content():DisplayObject
		{
			return _content;
		}
		
		public function get contentHeight():int
		{
			return _content.height;
		}
		
		public function set contentHeight(val:int):void
		{
			_contentHeight = val;
			
			updataContent();
		}
		
		public function get contentWidth():int
		{
			return _content.width;
		}
		
		public function set contentWidth(val:int):void
		{
			_contentWidth = val;
			
			updataContent();
		}
		
		/**高**/
		override public function get width():Number
		{
			return _width;
		}
		
		/**
		 * @private
		 */
		override public function set width(value:Number):void
		{
			_width = value;
			
			updataContent();
		}
		
		/**宽**/
		override public function get height():Number
		{
			return _height;
		}
		
		/**
		 * @private
		 */
		override public function set height(value:Number):void
		{
			_height = value;
			
			updataContent();
		}
		
		public function get maintainAspectRatio():Boolean
		{
			return _aspectRatio;
		}
		
		public function set maintainAspectRatio(val:Boolean):void
		{
			_aspectRatio = val;
			
			updataContent();
		}
		
		public function get scaleContent():Boolean
		{
			return _scaleContent;
		}
		
		public function set scaleContent(val:Boolean):void
		{
			_scaleContent = val;
			
			updataContent();
		}
		
		private function removeAll():void
		{
			var mc : MovieClip;
			while(numChildren > 0)
			{
				mc = getChildAt(0) as MovieClip;
				
				if( null != mc)
				{
					mc.stop();
				}
				
				removeChildAt(0);
			}
			
			if( _defaultImage is MovieClip)
			{
				MovieClip(_defaultImage).stop();
			}
			
			_content = null;
		}
		
		public function clear():void
		{
			_source = "";
			
			removeAll();
		}
		
		public function load():void
		{
			if(autoLoad) return;
			
			//开始加载
			loadRes();
		}
		
		
		/**
		 * 添加加载事件处理函数。只有在 autoLoad 设置为 False 且在调用load()前设置
		 * 才有效。
		 * @param func	：用于处理加载事件的函数。
		 * @param type	：加载事件的事件类型，支持：Event.COMPLETE、
		 * ProgressEvent.PROGRESS、HTTPStatusEvent.HTTP_STATUS、Event.INIT
		 * IOErrorEvent.IO_ERROR、Event.OPEN、Event.UNLOAD、Event.ADDED
		 * 
		 * */		
		public function addLoadedEvent(func:Function, type:String):void
		{
			for each(var event : Array in _eventList)
			{
				if(event[0] == type && event[1] == func)
				{
					return;
				}
			}
			_eventList.push([type, func]);
		}
		
		public function removeLoadedEvent(func:Function, type:String):void
		{
			var leng : int = _eventList.length;
			var event : Array;
			for (var i : int = 0; i < leng; i++)
			{
				event = _eventList[i];
				if(event[0] == type && event[1] == func)
				{
					_eventList.splice(i, 1);
					return;
				}
			}
		}
	}
}